package com.zhongli.devplatform.service.impl.user;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhongli.devplatform.bean.Res;
import com.zhongli.devplatform.component.wx.WeChatAuthUtil;
import com.zhongli.devplatform.dto.UserBindDTO;
import com.zhongli.devplatform.enums.SexType;
import com.zhongli.devplatform.mapper.clazz.ReadClazzMapper;
import com.zhongli.devplatform.mapper.sys.ReadRoleMapper;
import com.zhongli.devplatform.mapper.user.ReadUserInfoMapper;
import com.zhongli.devplatform.mapper.user.ReadUserMapper;
import com.zhongli.devplatform.mapper.user.ReadUserRoleMapper;
import com.zhongli.devplatform.po.common.ReadClazzPO;
import com.zhongli.devplatform.po.user.ReadRolePO;
import com.zhongli.devplatform.po.user.ReadUserInfoPO;
import com.zhongli.devplatform.po.user.ReadUserPO;
import com.zhongli.devplatform.po.user.ReadUserRolePO;
import com.zhongli.devplatform.security.qq.QQUserInfo;
import com.zhongli.devplatform.security.weixin.WxUserInfo;
import com.zhongli.devplatform.service.imp.user.UserRegisterService;
import com.zhongli.devplatform.utils.user.GenerateID;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.Objects;

/**
 * @author WuXiCheng
 * @version 1.0
 * @date 2020/8/19 10:27
 */
@Service
public class UserRegisterServiceImpl implements UserRegisterService {

    @Autowired
    private ReadUserMapper userMapper;

    @Autowired
    private ReadUserInfoMapper userInfoMapper;

    @Autowired
    private ReadRoleMapper roleMapper;

    @Autowired
    private ReadUserRoleMapper userRoleMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private ReadClazzMapper clazzMapper;

    @Autowired
    private WeChatAuthUtil weChatAuthUtil;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean bindUser(UserBindDTO userBindDTO) {
        boolean status = false;
        Integer type = userBindDTO.getType();
        ReadUserPO userPO;
        switch (type){
            case 1:
                userPO = userMapper.selectOne(new QueryWrapper<ReadUserPO>().eq("weixin_id",userBindDTO.getOpenId()));
                break;
            case 2:
                userPO = userMapper.selectOne(new QueryWrapper<ReadUserPO>().eq("qq_id",userBindDTO.getOpenId()));
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + type);
        }
        ReadUserInfoPO userInfoPO = userInfoMapper.selectOne(new QueryWrapper<ReadUserInfoPO>().eq("user_id", userPO.getId()));
        String role = roleMapper.selectOne(new QueryWrapper<ReadRolePO>().select("code").inSql("id",
                "SELECT role_id FROM read_user_role WHERE user_id =" + userPO.getId())).getCode();
        switch (role){
            case "student":
                ReadClazzPO clazzPO = clazzMapper.selectOne(new QueryWrapper<ReadClazzPO>().eq("invitation_code", userBindDTO.getInvitationCode()));
                if (!Objects.isNull(clazzPO)){
                    //绑定学校班级
                    userPO.setClazzId(clazzPO.getId());
                    userPO.setSchoolId(clazzPO.getSchoolId());
                    userPO.setAccountNum(userBindDTO.getPhone());
                    userMapper.updateById(userPO);
                    userInfoPO.setPhone(userBindDTO.getPhone());
                    userInfoMapper.updateById(userInfoPO);
                    status = true;
                }
                //绑定手机号
                break;
            case "parent":
                userPO.setAccountNum(userBindDTO.getPhone());
                userPO.setQqId(userBindDTO.getOpenId());
                userMapper.updateById(userPO);
                userInfoPO.setPhone(userBindDTO.getPhone());
                userInfoMapper.updateById(userInfoPO);
                status = true;
                break;
        }
        return status;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean wxRegister(JSONObject jsonObject,String role) {
        WxUserInfo wxUserInfo = new WxUserInfo();
        wxUserInfo.setOpenId(jsonObject.getString("openid"));
        wxUserInfo.setNickname(jsonObject.getString("nickname"));
        wxUserInfo.setHeadImg(jsonObject.getString("headimgurl"));
        wxUserInfo.setSex(jsonObject.getInteger("sex"));
        ReadUserPO userPO = userMapper.selectOne(new QueryWrapper<ReadUserPO>().eq("weixin_id", wxUserInfo.getOpenId()));
        if (Objects.isNull(userPO)) {
            ReadRolePO rolePO = roleMapper.selectOne(new QueryWrapper<ReadRolePO>().eq("code", role));
            if (!Objects.isNull(rolePO)){
                //初始化用户
                userPO = initUser();
                userPO.setWeixinId(wxUserInfo.getOpenId());
                userMapper.insert(userPO);

                //初始化用户信息
                ReadUserInfoPO userInfoPO = new ReadUserInfoPO();
                userInfoPO.setUserId(userPO.getId());
                userInfoPO.setNickName(wxUserInfo.getNickname());
                userInfoPO.setHeadImgUrl(wxUserInfo.getHeadImg());
                userInfoPO.setSex(SexType.values()[wxUserInfo.getSex()]);
                userInfoMapper.insert(userInfoPO);
                //初始化用户角色
                initUserRole(role, userPO, rolePO);
                return true;
            }
            throw new IllegalStateException("角色不存在");
        }
        return StringUtil.isBlank(userPO.getAccountNum());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean qqRegister(QQUserInfo qqUserInfo, String role) {
        ReadUserPO readUserPO = userMapper.selectOne(new QueryWrapper<ReadUserPO>().eq("qq_id", qqUserInfo.getOpenId()));
        if (Objects.isNull(readUserPO)){
            ReadRolePO rolePO = roleMapper.selectOne(new QueryWrapper<ReadRolePO>().eq("code", role));
            if (!Objects.isNull(rolePO)){
                //初始化用户
                ReadUserPO userPO = initUser();
                userPO.setQqId(qqUserInfo.getOpenId());
                userMapper.insert(userPO);

                //初始化用户信息
                ReadUserInfoPO userInfoPO = new ReadUserInfoPO();
                userInfoPO.setUserId(userPO.getId());
                userInfoPO.setNickName(qqUserInfo.getNickname());
                userInfoPO.setHeadImgUrl(qqUserInfo.getFigureurl_qq_1());
                SexType sex = "男".equals(qqUserInfo.getGender()) ? SexType.Male:SexType.Female;
                userInfoPO.setSex(sex);
                userInfoMapper.insert(userInfoPO);
                //初始化用户角色关系
                initUserRole(role, userPO, rolePO);
                return true;
            }
            throw new RuntimeException("角色不存在");
        }
        return StringUtil.isBlank(readUserPO.getAccountNum());
    }

    /**
     * 初始化用户
     * @return
     */
    private ReadUserPO initUser() {
        ReadUserPO userPO;
        userPO = new ReadUserPO();
        userPO.setSoleId(GenerateID.getGenerateID());
        userPO.setIsDelete(false);
        userPO.setIsEnable(true);
        userPO.setPassword(passwordEncoder.encode("123456"));
        userPO.setSkinType(1);
        return userPO;
    }

    /**
     * 初始化用户信息
     * @param role
     * @param userPO
     * @param rolePO
     */
    private void initUserRole(String role, ReadUserPO userPO, ReadRolePO rolePO) {
        ReadUserRolePO userRolePO = new ReadUserRolePO();
        //添加角色关系
        switch (role) {
            case "student":
            case "parent":
                userRolePO.setRoleId(rolePO.getId());
                userRolePO.setUserId(userPO.getId());
                userRoleMapper.insert(userRolePO);
                break;
        }
    }

    /**
     * 获取微信用户信息
     * @param accessToken
     * @param openId
     * @return
     */
    public Res getWxUserInfo(String accessToken, String openId) {
        String infoUrl = weChatAuthUtil.getUserInfoUrl(accessToken,openId);
        ReadUserInfoPO wxUserInfo = new ReadUserInfoPO();
        try {
            com.alibaba.fastjson.JSONObject userInfo = WeChatAuthUtil.doGetJson(infoUrl);
            if (!Objects.isNull(userInfo)) {
                //获取用户信息
                String nikeName = userInfo.getString("nickname");
                String sex = userInfo.getString("sex");
                String headimgurl = userInfo.getString("headimgurl");
                headimgurl.replace("\\", "");
                //初始化用户信息
                wxUserInfo.setNickName(nikeName);
                wxUserInfo.setHeadImgUrl(headimgurl);
                wxUserInfo.setSex("男".equals(sex)?SexType.Male:SexType.Female);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Res.ok(wxUserInfo);
    }

}
